package mao.thinkinjava.concurency.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
//模拟分步完成的工作的线程
public class PortionTask implements Runnable {
    private static int counter=0;
    private final int id = counter++;
    private static Random random = new Random(47);
    private CountDownLatch latch;

    public PortionTask(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try{
            doWork();
            latch.countDown();
            System.out.println(this+" countdown");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    public void doWork ()throws InterruptedException {
        TimeUnit.MICROSECONDS.sleep(random.nextInt(200));
        System.out.println(this+"complete work");
    }

    @Override
    public String toString() {
        return "PortionTask{" +
                "id=" + id +
                '}';
    }
}
